import {observable, action, computed} from 'mobx';
import {request} from '../utils/axios';
import store from 'store'
import {baseConfig} from '../utils/constants'

const USERANDPWD = '__zycfUserAndPwd__';
const USERSTATE = '__zycfUserState__';

export default class UserState {
  @observable loginUser;
  @observable password;

  constructor() {
    this.loginUser = store.get(baseConfig.store.USER_STATE) || {};
    this.password = store.get(baseConfig.store.USER_PASSWORD) || {};
  }

  /**
   * ******************************http request******************************
   * */

  async login(value) {
    const {data} = await request(
      {
        method: 'post',
        url: '/api/sysUser/login',
        data: {
          loginId: value.loginName,
          password: value.password
        },
      },
      {message: '登录成功'},
      {message: '登录失败'}
    )

    // 取得认证信息
    const tokenData = await request(
      {
        method: 'post',
        url: '/api/token',
        data: {
          loginId: value.loginName,
          password: value.password
        },
      },
      {message: '用户认证成功'},
      {message: '用户认证失败'}
    )

    store.set(baseConfig.store.USER_TOKEN,tokenData.data.data.token);

    this.setLoginUser(data);
    this.setPassword(value);
    return data;
  }

  /**
   * ******************************action******************************
   * */

  @action
  setLoginUser(data) {
    store.set(baseConfig.store.USER_STATE, data)
    this.loginUser = data;
  }

  /**
   * 记住密码时，储存用户和密码
   * 密码储存在localStorage，暂时未做加密处理
   * */
  @action
  setPassword(data) {
    // 记住密码
    if (data.password) {
      store.set(baseConfig.store.USER_PASSWORD, data)
      this.password = data;
    } else { // 删除记住在本地的密码
      store.remove(baseConfig.store.USER_PASSWORD)
      this.password = {};
    }
  }

  /**
   * 退出登录
   * */
  @action
  outLogin() {
    store.remove(baseConfig.store.USER_STATE)
    this.loginUser = {};
  }
}
